{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "Path = \"hdfs://XX:8020/u01/bigdata/\"\n",
    "raw_data = sc.textFile(Path + \"data/train_noheader.tsv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#raw_data.take(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7395"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "numRaw = raw_data.count()\n",
    "numRaw"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defaultdict(int, {u'\"': 7395})"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "raw_data.countByKey()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[u'\"http://www.bloomberg.com/news/2010-12-23/ibm-predicts-holographic-calls-air-breathing-batteries-by-2015.html\"',\n",
       " u'\"4042\"',\n",
       " u'\"{\"\"title\"\":\"\"IBM Sees Holographic Calls Air Breathing Batteries ibm sees holographic calls, air-breathing batteries\"\",\"\"body\"\":\"\"A sign stands outside the International Business Machines Corp IBM Almaden Research Center campus in San Jose California Photographer Tony Avelar Bloomberg Buildings stand at the International Business Machines Corp IBM Almaden Research Center campus in the Santa Teresa Hills of San Jose California Photographer Tony Avelar Bloomberg By 2015 your mobile phone will project a 3 D image of anyone who calls and your laptop will be powered by kinetic energy At least that s what International Business Machines Corp sees in its crystal ball The predictions are part of an annual tradition for the Armonk New York based company which surveys its 3 000 researchers to find five ideas expected to take root in the next five years IBM the world s largest provider of computer services looks to Silicon Valley for input gleaning many ideas from its Almaden research center in San Jose California Holographic conversations projected from mobile phones lead this year s list The predictions also include air breathing batteries computer programs that can tell when and where traffic jams will take place environmental information generated by sensors in cars and phones and cities powered by the heat thrown off by computer servers These are all stretch goals and that s good said Paul Saffo managing director of foresight at the investment advisory firm Discern in San Francisco In an era when pessimism is the new black a little dose of technological optimism is not a bad thing For IBM it s not just idle speculation The company is one of the few big corporations investing in long range research projects and it counts on innovation to fuel growth Saffo said Not all of its predictions pan out though IBM was overly optimistic about the spread of speech technology for instance When the ideas do lead to products they can have broad implications for society as well as IBM s bottom line he said Research Spending They have continued to do research when all the other grand research organizations are gone said Saffo who is also a consulting associate professor at Stanford University IBM invested 5 8 billion in research and development last year 6 1 percent of revenue While that s down from about 10 percent in the early 1990s the company spends a bigger share on research than its computing rivals Hewlett Packard Co the top maker of personal computers spent 2 4 percent last year At Almaden scientists work on projects that don t always fit in with IBM s computer business The lab s research includes efforts to develop an electric car battery that runs 500 miles on one charge a filtration system for desalination and a program that shows changes in geographic data IBM rose 9 cents to 146 04 at 11 02 a m in New York Stock Exchange composite trading The stock had gained 11 percent this year before today Citizen Science The list is meant to give a window into the company s innovation engine said Josephine Cheng a vice president at IBM s Almaden lab All this demonstrates a real culture of innovation at IBM and willingness to devote itself to solving some of the world s biggest problems she said Many of the predictions are based on projects that IBM has in the works One of this year s ideas that sensors in cars wallets and personal devices will give scientists better data about the environment is an expansion of the company s citizen science initiative Earlier this year IBM teamed up with the California State Water Resources Control Board and the City of San Jose Environmental Services to help gather information about waterways Researchers from Almaden created an application that lets smartphone users snap photos of streams and creeks and report back on conditions The hope is that these casual observations will help local and state officials who don t have the resources to do the work themselves Traffic Predictors IBM also sees data helping shorten commutes in the next five years Computer programs will use algorithms and real time traffic information to predict which roads will have backups and how to avoid getting stuck Batteries may last 10 times longer in 2015 than today IBM says Rather than using the current lithium ion technology new models could rely on energy dense metals that only need to interact with the air to recharge Some electronic devices might ditch batteries altogether and use something similar to kinetic wristwatches which only need to be shaken to generate a charge The final prediction involves recycling the heat generated by computers and data centers Almost half of the power used by data centers is currently spent keeping the computers cool IBM scientists say it would be better to harness that heat to warm houses and offices In IBM s first list of predictions compiled at the end of 2006 researchers said instantaneous speech translation would become the norm That hasn t happened yet While some programs can quickly translate electronic documents and instant messages and other apps can perform limited speech translation there s nothing widely available that acts like the universal translator in Star Trek Second Life The company also predicted that online immersive environments such as Second Life would become more widespread While immersive video games are as popular as ever Second Life s growth has slowed Internet users are flocking instead to the more 2 D environments of Facebook Inc and Twitter Inc Meanwhile a 2007 prediction that mobile phones will act as a wallet ticket broker concierge bank and shopping assistant is coming true thanks to the explosion of smartphone applications Consumers can pay bills through their banking apps buy movie tickets and get instant feedback on potential purchases all with a few taps on their phones The nice thing about the list is that it provokes thought Saffo said If everything came true they wouldn t be doing their job To contact the reporter on this story Ryan Flinn in San Francisco at rflinn bloomberg net To contact the editor responsible for this story Tom Giles at tgiles5 bloomberg net by 2015, your mobile phone will project a 3-d image of anyone who calls and your laptop will be powered by kinetic energy. at least that\\\\u2019s what international business machines corp. sees in its crystal ball.\"\",\"\"url\"\":\"\"bloomberg news 2010 12 23 ibm predicts holographic calls air breathing batteries by 2015 html\"\"}\"',\n",
       " u'\"business\"',\n",
       " u'\"0.789131\"',\n",
       " u'\"2.055555556\"',\n",
       " u'\"0.676470588\"',\n",
       " u'\"0.205882353\"',\n",
       " u'\"0.047058824\"',\n",
       " u'\"0.023529412\"',\n",
       " u'\"0.443783175\"',\n",
       " u'\"0\"',\n",
       " u'\"0\"',\n",
       " u'\"0.09077381\"',\n",
       " u'\"0\"',\n",
       " u'\"0.245831182\"',\n",
       " u'\"0.003883495\"',\n",
       " u'\"1\"',\n",
       " u'\"1\"',\n",
       " u'\"24\"',\n",
       " u'\"0\"',\n",
       " u'\"5424\"',\n",
       " u'\"170\"',\n",
       " u'\"8\"',\n",
       " u'\"0.152941176\"',\n",
       " u'\"0.079129575\"',\n",
       " u'\"0\"']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "records = raw_data.map(lambda line: line.split('\\t'))\n",
    "records.first()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "27"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(records.first())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[u'\"http://www.bloomberg.com/news/2010-12-23/ibm-predicts-holographic-calls-air-breathing-batteries-by-2015.html\"',\n",
       " u'\"4042\"',\n",
       " u'\"{\"\"title\"\":\"\"IBM Sees Holographic Calls Air Breathing Batteries ibm sees holographic calls, air-breathing batteries\"\",\"\"body\"\":\"\"A sign stands outside the International Business Machines Corp IBM Almaden Research Center campus in San Jose California Photographer Tony Avelar Bloomberg Buildings stand at the International Business Machines Corp IBM Almaden Research Center campus in the Santa Teresa Hills of San Jose California Photographer Tony Avelar Bloomberg By 2015 your mobile phone will project a 3 D image of anyone who calls and your laptop will be powered by kinetic energy At least that s what International Business Machines Corp sees in its crystal ball The predictions are part of an annual tradition for the Armonk New York based company which surveys its 3 000 researchers to find five ideas expected to take root in the next five years IBM the world s largest provider of computer services looks to Silicon Valley for input gleaning many ideas from its Almaden research center in San Jose California Holographic conversations projected from mobile phones lead this year s list The predictions also include air breathing batteries computer programs that can tell when and where traffic jams will take place environmental information generated by sensors in cars and phones and cities powered by the heat thrown off by computer servers These are all stretch goals and that s good said Paul Saffo managing director of foresight at the investment advisory firm Discern in San Francisco In an era when pessimism is the new black a little dose of technological optimism is not a bad thing For IBM it s not just idle speculation The company is one of the few big corporations investing in long range research projects and it counts on innovation to fuel growth Saffo said Not all of its predictions pan out though IBM was overly optimistic about the spread of speech technology for instance When the ideas do lead to products they can have broad implications for society as well as IBM s bottom line he said Research Spending They have continued to do research when all the other grand research organizations are gone said Saffo who is also a consulting associate professor at Stanford University IBM invested 5 8 billion in research and development last year 6 1 percent of revenue While that s down from about 10 percent in the early 1990s the company spends a bigger share on research than its computing rivals Hewlett Packard Co the top maker of personal computers spent 2 4 percent last year At Almaden scientists work on projects that don t always fit in with IBM s computer business The lab s research includes efforts to develop an electric car battery that runs 500 miles on one charge a filtration system for desalination and a program that shows changes in geographic data IBM rose 9 cents to 146 04 at 11 02 a m in New York Stock Exchange composite trading The stock had gained 11 percent this year before today Citizen Science The list is meant to give a window into the company s innovation engine said Josephine Cheng a vice president at IBM s Almaden lab All this demonstrates a real culture of innovation at IBM and willingness to devote itself to solving some of the world s biggest problems she said Many of the predictions are based on projects that IBM has in the works One of this year s ideas that sensors in cars wallets and personal devices will give scientists better data about the environment is an expansion of the company s citizen science initiative Earlier this year IBM teamed up with the California State Water Resources Control Board and the City of San Jose Environmental Services to help gather information about waterways Researchers from Almaden created an application that lets smartphone users snap photos of streams and creeks and report back on conditions The hope is that these casual observations will help local and state officials who don t have the resources to do the work themselves Traffic Predictors IBM also sees data helping shorten commutes in the next five years Computer programs will use algorithms and real time traffic information to predict which roads will have backups and how to avoid getting stuck Batteries may last 10 times longer in 2015 than today IBM says Rather than using the current lithium ion technology new models could rely on energy dense metals that only need to interact with the air to recharge Some electronic devices might ditch batteries altogether and use something similar to kinetic wristwatches which only need to be shaken to generate a charge The final prediction involves recycling the heat generated by computers and data centers Almost half of the power used by data centers is currently spent keeping the computers cool IBM scientists say it would be better to harness that heat to warm houses and offices In IBM s first list of predictions compiled at the end of 2006 researchers said instantaneous speech translation would become the norm That hasn t happened yet While some programs can quickly translate electronic documents and instant messages and other apps can perform limited speech translation there s nothing widely available that acts like the universal translator in Star Trek Second Life The company also predicted that online immersive environments such as Second Life would become more widespread While immersive video games are as popular as ever Second Life s growth has slowed Internet users are flocking instead to the more 2 D environments of Facebook Inc and Twitter Inc Meanwhile a 2007 prediction that mobile phones will act as a wallet ticket broker concierge bank and shopping assistant is coming true thanks to the explosion of smartphone applications Consumers can pay bills through their banking apps buy movie tickets and get instant feedback on potential purchases all with a few taps on their phones The nice thing about the list is that it provokes thought Saffo said If everything came true they wouldn t be doing their job To contact the reporter on this story Ryan Flinn in San Francisco at rflinn bloomberg net To contact the editor responsible for this story Tom Giles at tgiles5 bloomberg net by 2015, your mobile phone will project a 3-d image of anyone who calls and your laptop will be powered by kinetic energy. at least that\\\\u2019s what international business machines corp. sees in its crystal ball.\"\",\"\"url\"\":\"\"bloomberg news 2010 12 23 ibm predicts holographic calls air breathing batteries by 2015 html\"\"}\"',\n",
       " u'\"business\"',\n",
       " u'\"0.789131\"',\n",
       " u'\"2.055555556\"',\n",
       " u'\"0.676470588\"',\n",
       " u'\"0.205882353\"',\n",
       " u'\"0.047058824\"',\n",
       " u'\"0.023529412\"',\n",
       " u'\"0.443783175\"',\n",
       " u'\"0\"',\n",
       " u'\"0\"',\n",
       " u'\"0.09077381\"',\n",
       " u'\"0\"',\n",
       " u'\"0.245831182\"',\n",
       " u'\"0.003883495\"',\n",
       " u'\"1\"',\n",
       " u'\"1\"',\n",
       " u'\"24\"',\n",
       " u'\"0\"',\n",
       " u'\"5424\"',\n",
       " u'\"170\"',\n",
       " u'\"8\"',\n",
       " u'\"0.152941176\"',\n",
       " u'\"0.079129575\"',\n",
       " u'\"0\"']"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = records.collect()\n",
    "data[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "27"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "numColumns = len(data[0])\n",
    "numColumns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyspark.ml.linalg import Vectors\n",
    "from pyspark.ml.classification import DecisionTreeClassifier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "data1 = []\n",
    "for i in range(numRaw):\n",
    "    trimmed = [ each.replace('\"', \"\") for each in data[i] ]\n",
    "    label = int(trimmed[-1])\n",
    "    features = map(lambda x: 0.0 if x == \"?\" else x, trimmed[4: numColumns-1])\n",
    "    c = (label, Vectors.dense(map(float, features)))\n",
    "    data1.append(c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0,\n",
       " DenseVector([0.7891, 2.0556, 0.6765, 0.2059, 0.0471, 0.0235, 0.4438, 0.0, 0.0, 0.0908, 0.0, 0.2458, 0.0039, 1.0, 1.0, 24.0, 0.0, 5424.0, 170.0, 8.0, 0.1529, 0.0791]))"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data1[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+-----+--------------------+\n",
      "|label|            features|\n",
      "+-----+--------------------+\n",
      "|    0|[0.789131,2.05555...|\n",
      "|    1|[0.574147,3.67796...|\n",
      "+-----+--------------------+\n",
      "only showing top 2 rows\n",
      "\n"
     ]
    }
   ],
   "source": [
    "df = spark.createDataFrame(data1, [\"label\", \"features\"])\n",
    "df.show(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "root\n",
      " |-- label: long (nullable = true)\n",
      " |-- features: vector (nullable = true)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "df.printSchema()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DataFrame[label: bigint, features: vector]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.cache()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyspark.ml.feature import VectorIndexer\n",
    "featureIndexer = VectorIndexer(inputCol=\"features\", outputCol=\"indexedFeatures\", maxCategories=24).fit(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "(trainData, testData) = df.randomSplit([0.8, 0.2], seed=1234L) #seed=1234L表示每次生成的训练集和测试集总行数不变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5935"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainData.count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1460"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "testData.count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "dt = DecisionTreeClassifier(maxDepth=5, labelCol=\"label\", featuresCol=\"indexedFeatures\", impurity=\"entropy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyspark.ml import Pipeline\n",
    "pipeline = Pipeline(stages = [featureIndexer, dt])\n",
    "model = pipeline.fit(trainData)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+--------------------+--------------------+-------------+--------------------+----------+\n",
      "|            features|     indexedFeatures|rawPrediction|         probability|prediction|\n",
      "+--------------------+--------------------+-------------+--------------------+----------+\n",
      "|[0.789131,2.05555...|[0.789131,2.05555...|[564.0,578.0]|[0.49387040280210...|       1.0|\n",
      "+--------------------+--------------------+-------------+--------------------+----------+\n",
      "\n"
     ]
    }
   ],
   "source": [
    "test0 = spark.createDataFrame([(data1[0][1],)], [\"features\"])\n",
    "result = model.transform(test0)\n",
    "result.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+----------+\n",
      "|prediction|\n",
      "+----------+\n",
      "|       1.0|\n",
      "+----------+\n",
      "\n"
     ]
    }
   ],
   "source": [
    "result.select(['prediction']).show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.789131"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "firstRaw = list(data1[0][1])\n",
    "firstRaw[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.055555556"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "firstRaw[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DenseVector([0.7891, 2.0556, 0.6765, 0.2059, 0.0471, 0.0235, 0.4438, 0.0, 0.0, 0.0908, 0.0, 0.2458, 0.0039, 1.0, 1.0, 24.0, 0.0, 5424.0, 170.0, 8.0, 0.1529, 0.0791])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predictData = Vectors.dense(firstRaw)\n",
    "predictData"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+--------------------+--------------------+-------------+--------------------+----------+\n",
      "|            features|     indexedFeatures|rawPrediction|         probability|prediction|\n",
      "+--------------------+--------------------+-------------+--------------------+----------+\n",
      "|[0.789131,2.05555...|[0.789131,2.05555...|[564.0,578.0]|[0.49387040280210...|       1.0|\n",
      "+--------------------+--------------------+-------------+--------------------+----------+\n",
      "\n"
     ]
    }
   ],
   "source": [
    "predictRaw = spark.createDataFrame([(predictData,)], [\"features\"])\n",
    "predictResult = model.transform(predictRaw)\n",
    "predictResult.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "+----------+\n",
      "|prediction|\n",
      "+----------+\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       1.0|\n",
      "|       0.0|\n",
      "|       1.0|\n",
      "|       0.0|\n",
      "|       1.0|\n",
      "|       0.0|\n",
      "|       1.0|\n",
      "|       1.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       0.0|\n",
      "|       1.0|\n",
      "|       0.0|\n",
      "+----------+\n",
      "only showing top 20 rows\n",
      "\n"
     ]
    }
   ],
   "source": [
    "predictResultAll = model.transform(testData)\n",
    "predictResultAll.select(['prediction']).show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0]"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_predict = predictResultAll.select(['prediction']).toPandas()\n",
    "dtPredict = list(df_predict.prediction)\n",
    "dtPredict[:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dtTotalCorrect = 0\n",
    "testRaw = testData.count();\n",
    "#testLabel = testData.select(\"label\").collect()\n",
    "df_test = testData.select(['label']).toPandas()\n",
    "testLabel = list(df_test.label)\n",
    "testLabel[:10]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "933"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "for i in range(testRaw):\n",
    "    if dtPredict[i] == testLabel[i]:\n",
    "        dtTotalCorrect += 1\n",
    "dtTotalCorrect"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6390410958904109"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1.0 * dtTotalCorrect / testRaw "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyspark.ml.linalg import Vectors\n",
    "from pyspark.ml.feature import VectorIndexer\n",
    "from pyspark.ml import Pipeline\n",
    "raw_data = sc.textFile(Path + \"data/train_noheader.tsv\")\n",
    "numRaw = raw_data.count()\n",
    "records = raw_data.map(lambda line: line.split('\\t'))\n",
    "data = records.collect()\n",
    "numColumns = len(data[0])\n",
    "data1 = []"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[u'?',\n",
       " u'arts_entertainment',\n",
       " u'business',\n",
       " u'computer_internet',\n",
       " u'culture_politics',\n",
       " u'gaming',\n",
       " u'health',\n",
       " u'law_crime',\n",
       " u'recreation',\n",
       " u'religion',\n",
       " u'science_technology',\n",
       " u'sports',\n",
       " u'unknown',\n",
       " u'weather']"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "category = records.map(lambda x: x[3].replace(\"\\\"\", \"\"))\n",
    "categories = sorted(category.distinct().collect())\n",
    "categories"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "numCategories = len(categories)\n",
    "numCategories"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "def transform_category(x):\n",
    "    markCategory = [0] * numCategories\n",
    "    index = categories.index(x)\n",
    "    markCategory[index] = 1\n",
    "    return markCategory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(numRaw):\n",
    "    trimmed = [ each.replace('\"', \"\") for each in data[i] ]\n",
    "    label = int(trimmed[-1])\n",
    "    cate = transform_category(trimmed[3])\n",
    "    features = cate + map(lambda x: 0.0 if x == \"?\" else x, trimmed[4: numColumns-1]) #只取第5到27列\n",
    "    c = (label, Vectors.dense(map(float, features)))\n",
    "    data1.append(c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DataFrame[label: bigint, features: vector]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = spark.createDataFrame(data1, [\"label\", \"features\"])\n",
    "df.cache()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "featureIndexer = VectorIndexer(inputCol=\"features\", outputCol=\"indexedFeatures\", maxCategories=24).fit(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5935"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(trainData, testData) = df.randomSplit([0.8, 0.2], seed=1234L) #seed=1234L表示每次生成的训练集和测试集总行数不变\n",
    "trainData.count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1460"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "testData.count()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "dt = DecisionTreeClassifier(maxDepth=5, labelCol=\"label\", featuresCol=\"indexedFeatures\", impurity=\"entropy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline = Pipeline(stages = [featureIndexer, dt])\n",
    "model = pipeline.fit(trainData) #训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6390410958904109"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dtTotalCorrect = 0\n",
    "testRaw = testData.count();\n",
    "#testLabel = testData.select(\"label\").collect() #这个获取的row不是list？版本原因\n",
    "df_test = testData.select(['label']).toPandas()\n",
    "testLabel = list(df_test.label)\n",
    "\n",
    "for i in range(testRaw):\n",
    "    if dtPredict[i] == testLabel[i]:\n",
    "        dtTotalCorrect += 1\n",
    "\n",
    "1.0 * dtTotalCorrect / testRaw "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6363013698630137"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#导入交叉验证和参数网格\n",
    "from pyspark.ml.tuning import CrossValidator, ParamGridBuilder\n",
    "#导入二分类评估器\n",
    "from pyspark.ml.evaluation import BinaryClassificationEvaluator\n",
    "evaluator = BinaryClassificationEvaluator() #初始化一个评估器\n",
    "#设置参数网格\n",
    "paramGrid = ParamGridBuilder().addGrid(dt.maxDepth, [4,5,6]).build()\n",
    "#设置交叉认证的参数\n",
    "crossval = CrossValidator(estimator=pipeline,\n",
    "                  estimatorParamMaps=paramGrid,\n",
    "                  evaluator=evaluator,\n",
    "                  numFolds=2)  # use 3+ folds in practice\n",
    "\n",
    "# 通过交叉认证来训练模型, and choose the best set of parameters.\n",
    "cvModel = crossval.fit(trainData)\n",
    "# 测试模型\n",
    "predictResultAll = cvModel.transform(testData)\n",
    "df_predict = predictResultAll.select(['prediction']).toPandas()\n",
    "dtPredict = list(df_predict.prediction)\n",
    "\n",
    "dtTotalCorrect = 0\n",
    "testRaw = testData.count();\n",
    "df_test = testData.select(['label']).toPandas()\n",
    "testLabel = list(df_test.label)\n",
    "\n",
    "for i in range(testRaw):\n",
    "    if dtPredict[i] == testLabel[i]:\n",
    "        dtTotalCorrect += 1\n",
    "\n",
    "1.0 * dtTotalCorrect / testRaw"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DecisionTreeClassificationModel (uid=DecisionTreeClassifier_49be9e0a62a2d27f1978) of depth 4 with 31 nodes"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bestModel = cvModel.bestModel.stages[1]\n",
    "bestModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "36"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bestModel.numFeatures"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bestModel.depth"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "31"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bestModel.numNodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}